import { mergeWith, isObject, isArray, get, dropRight } from 'lodash'
import apply from 'lodash/_apply.js'
import baseRest from 'lodash/_baseRest'
import baseMerge from 'lodash/_baseMerge'

function customDefaultsMerge (objValue, srcValue, key, object, source, stack) {
  if (isObject(objValue) && isObject(srcValue)) {
    if (isArray(objValue) && isArray(srcValue)) {
      return objValue
    }
    stack.set(srcValue, objValue)
    baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack)
    stack['delete'](srcValue)
  }
  return objValue
}

// 对Object进行深度合并，对其他类型进行替换
export const mergeDeep = baseRest(function (args) {
  args.push(undefined, customDefaultsMerge)
  return apply(mergeWith, undefined, args)
})

// 把公共层、模块层、页面层等columns合并成一个columns
export const getColumns = (config, deepList) => {
  return deepList.reduce((result, deep, index) => {
    return mergeDeep(get(config, dropRight(deepList, index)).columns, result)
  }, {})
}

/*
  配置合成函数
  desc: 合成master和project里的具体页面配置
  props:
    config: 具体配置
    deepList: 页面模块路径
  1.对页面里非columns的配置进行合并
  2.对columns的配置先纵向合并，再合并master和project
*/
export const extendDeep = (config, deepList) => {
  // 合并除了columns外的其它页面配置
  const others = mergeDeep(get(config.project, deepList), get(config.master, deepList))
  // 合并页面的columns配置
  const columns = mergeDeep(getColumns(config.project, deepList), getColumns(config.master, deepList))
  return {
    ...others,
    columns
  }
}
